package com.ygqh.baby.service.impl;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.Message.Type;
import com.ygqh.baby.model.YgCouponPageModel;
import com.ygqh.baby.model.YgProductModel;
import com.ygqh.baby.model.YgSimilarityPublishModel;
import com.ygqh.baby.po.YgGroup;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.FileService;
import com.ygqh.baby.service.FreemarkerService;
import com.ygqh.baby.service.YgGroupService;
import com.ygqh.baby.service.YgProductCommentService;
import com.ygqh.baby.service.YgProductService;
import com.ygqh.baby.service.YgPublishService;
import com.ygqh.baby.utils.DateConvertUtils;
import com.ygqh.baby.utils.ExceptionUtil;
import com.ygqh.baby.utils.MailUtil;

@Component
public class GenerateStaticPages {

	protected Logger logger = Logger.getLogger(this.getClass());
	@Autowired
	private YgProductService ygProductService;

	@Autowired
	private YgGroupService ygGroupService;
	@Autowired
	private RedisDao redisDao;
	@Autowired
	private YgPublishService ygPublishService;
	@Autowired
	private YgProductCommentService ygProductCommentService;
	@Autowired
	private FreemarkerService freemarkerService;
	@Autowired
	private FileService fileService;
	@Autowired
	private MailUtil mailUtil;

	@Value("${image.upload.temp.url}")
	private String tempUrl;
	@Value("${oss.aliyun.endpoint}")
	private String endpoint;
	@Value("${oss.aliyun.templatebucketName}")
	private String templatebucketName;
	@Value("${product.template.filename}")
	private String templateFileName;

	public Message reviewPage(Long... productIds) {
		Map<Long, String> errorMap = null;
		if (productIds != null && productIds.length > 0) {
			for (Long productId : productIds) {
				try {
					this.excute(productId, productId + ".html");
				} catch (Exception e) {
					if (errorMap == null) {
						errorMap = new HashMap<>();
					}
					logger.error(ExceptionUtil.getExceptionMsg(e));
					errorMap.put(productId, "异常类型：" + e.getClass().getName() + "【" + e.getMessage() + "】");
					e.printStackTrace();
				}
			}

		}
		if (errorMap != null) {
			this.sendMall(errorMap);
			return Message.error(errorMap);
		}
		return Message.success(null);

	}

	private Message excute(Long productId, String filename) throws Exception {

		Map<String, Object> data = new HashMap<String, Object>();
		// 获取产品detail 数据
		YgProductModel detail = ygProductService.findDetailModel(productId);
		if (detail.getPromotionPrice() != null && detail.getPromotionPrice().doubleValue() > 0) {
			detail.setProductSalePrice(detail.getPromotionPrice());
			detail.setProductOriginalPrice(detail.getProductSalePrice());
		}
		data.put("productCode", detail.getProductCode());
		data.put("isSpecial", detail.getIsSpecial());
		SimpleDateFormat sdf = new SimpleDateFormat("MM月dd日");
		data.put("preSaleDate", detail.getPreSaleDate() == null ? "0" : sdf.format(detail.getPreSaleDate()));
		data.put("productDetail", detail);
		data.put("timestamp", System.currentTimeMillis());
		// 判断商品类型
		String saleTitle = "";
		if (detail.getProductType().equals("JiaJiaGou")) {
			saleTitle = "加价购商品不能单独购买";
		}
		;
		// 赠品不可以销售
		if (detail.getProductType().equals("ManZeng")) {
			saleTitle = "赠品不能单独购买";
		}
		;
		// 下架商品部可以销售
		if (detail.getSaleStatus().equals("InStock")) {
			saleTitle = "商品已售罄";
		}
		;
		data.put("saleTitle", saleTitle);

		// 获取花色
		List<Map<String, Object>> colorList = ygProductService.findProductByGroupId(0L, detail.getGroupId());
		data.put("colorList", colorList);
		// 判断是否拼团商品
		if (detail.getPromotionPrice() != null && detail.getPromotionPrice().doubleValue() > 0) {
			YgGroup group = ygGroupService.findById(detail.getGroupId());
			data.put("groupAmount", group.getGroupAmount());
		} else {
			data.put("groupAmount", 0);
		}
		String couponPage = redisDao.get("CouponPage");
		if (StringUtil.isNotBlank(couponPage)) {
			data.put("couponPage", JSONObject.parseObject(couponPage, YgCouponPageModel.class));
		}

		// 相似晒单
		List<YgSimilarityPublishModel> result = ygPublishService.findSimilarityPublishModel(productId, detail.getGroupId(), 67L);
		data.put("publishModel", result);
		// 评论数
		int commentCount = ygProductCommentService.commentCount(detail.getGroupId());
		data.put("commentCount", commentCount);
		// 生成html

		String dirPath = DateConvertUtils.format(new Date());
		String msg = freemarkerService.crateHTML(templateFileName, dirPath, filename, data);
		if (msg != "")
			return new Message(Type.error, msg);
		// 获取html 上传到oss
		fileService.uploadHtml2Oss(filename, tempUrl + "/" + dirPath + "/" + filename);

		return Message.success("预览", "");

	}

	public void sendMall(Map<Long, String> errorMap) {

		StringBuffer str = new StringBuffer();
		str.append(
				"<html><head><style>.table-d table{ background:#000;font-size:14px} .table-d table td{ background:#FFF} h5{width: auto;margin-right: 20px} .title{display: flex;line-height: 10px}");
		str.append("</style></head><body>");
		str.append("<div class='table-d'>");
		str.append("<table width='500' border='0' cellspacing='1' cellpadding='0'><tr><td width='15%'>商品id</td>" + "<td width='15%'>错误内容</td></tr>");
		for (Entry<Long, String> entry : errorMap.entrySet()) {

			str.append("<tr><td>" + entry.getKey() + "</td>");
			str.append("<td>" + entry.getValue() + "</td></tr>");
		}
		str.append("</table>");
		try {
			mailUtil.sendWithHtml(new String[] { "guohao@yiigoo.com", "jiangyunbo@yiigoo.com" }, "单品页静态文件生成失败", str.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
